<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        .sidebar {
            height: 100vh;
            background-color: #343a40;
            color: white;
            transition: all 0.3s;
            position: fixed;
            left: 0;
            top: 0;
            width: 250px;
            z-index: 1000;
        }
        .sidebar.collapsed {
            width: 60px;
        }
        .sidebar-header {
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid #555;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .sidebar-header h4 {
            margin: 0;
            transition: all 0.3s;
            white-space: nowrap;
        }
        .sidebar.collapsed .sidebar-header h4 {
            display: none;
        }
        .sidebar-menu {
            padding: 20px 0;
            flex-grow: 1;
            overflow-y: auto;
        }
        .sidebar-footer {
            padding: 10px;
            text-align: center;
            font-size: 0.8rem;
            border-top: 1px solid #555;
        }
        .sidebar.collapsed .sidebar-footer {
            font-size: 0;
        }
        .nav-link {
            color: rgba(255, 255, 255, 0.75);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: flex;
            align-items: center;
            text-decoration: none;
        }
        .nav-link i {
            margin-right: 10px;
            font-size: 1.2rem;
            width: 25px;
            text-align: center;
        }
        .sidebar.collapsed .nav-link span {
            display: none;
        }
        .nav-link:hover {
            color: white;
        }
        .nav-link:focus,
        .nav-link:active {
            color: rgba(255, 255, 255, 0.75);
        }
        .nav-link.active {
            color: #0d6efd !important;
            background-color: #495057;
        }
        .nav-link.active:hover {
            color: #0d6efd !important;
        }
        .main-content {
            min-height: 100vh;
            overflow-y: auto;
            margin-left: 250px;
            transition: all 0.3s;
            width: calc(100% - 250px);
        }
        .main-content.expanded {
            margin-left: 60px;
            width: calc(100% - 60px);
        }
        .top-nav {
            height: 60px;
            border-bottom: 1px solid #e0e0e0;
        }
        .toggle-sidebar {
            cursor: pointer;
            font-size: 1.5rem;
        }
        #tabs-container {
            background-color: #f8f9fa;
            padding: 10px 15px 0;
            border-bottom: 1px solid #dee2e6;
            display: flex;
            overflow-y: hidden;
            white-space: nowrap;
        }
        .nav-tab {
            display: inline-block;
            padding: 8px 15px;
            margin-right: 5px;
            background-color: #e9ecef;
            border-radius: 5px 5px 0 0;
            cursor: pointer;
            position: relative;
        }
        .nav-tab.active {
            background-color: #ffffff;
            border: 1px solid #dee2e6;
            border-bottom: 1px solid #fff;
            margin-bottom: -1px;
        }
        .nav-tab .close-tab {
            margin-left: 10px;
            opacity: 0.5;
        }
        .nav-tab .close-tab:hover {
            opacity: 1;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        
        /* 子菜单样式 */
        .submenu {
            list-style: none;
            padding-left: 0;
            display: none;
            max-height: 0;
            transition: max-height 0.3s ease-out;
        }
        .submenu.show {
            display: block;
            max-height: 500px;
            transition: max-height 0.5s ease-in;
        }
        .sidebar.collapsed .submenu {
            display: none;
        }
        .sidebar.collapsed .has-submenu > a::after {
            display: none;
        }
        .has-submenu > a::after {
            content: '\F282';
            font-family: 'bootstrap-icons';
            margin-left: auto;
            transition: transform 0.3s;
        }
        .has-submenu.open > a::after {
            transform: rotate(90deg);
        }
        .submenu .nav-link {
            padding-left: 45px;
            font-size: 0.9rem;
        }
        
        /* 移动端适配 */
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                transform: translateX(-100%);
            }
            .sidebar.show {
                transform: translateX(0);
            }
            .sidebar.show .sidebar-header h4 {
                display: block;
            }
            .sidebar.show .nav-link span {
                display: inline;
            }
            .main-content {
                margin-left: 0;
                width: 100%;
            }
            .mobile-nav {
                display: flex;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                background-color: #343a40;
                color: white;
                height: 60px;
                z-index: 999;
                align-items: center;
                padding: 0 15px;
            }
            .mobile-menu-toggle {
                font-size: 1.5rem;
                cursor: pointer;
            }
            .main-content {
                padding-top: 60px;
            }
        }
        #iframe-container {
            position: relative;
            width: 100%;
            height: calc(100vh - 150px);
            overflow: auto;
            overflow-y: hidden;
        }
        .tab-iframe {
            width: 100%;
            height: 100%;
            border: none;
            display: none;
            overflow: auto;
            overflow-y: hidden;
        }
    </style>
</head>
<body>
    <!-- 移动端导航 -->
    <div class="mobile-nav d-md-none">
        <div class="mobile-menu-toggle" id="mobile-menu-toggle">
            <i class="bi bi-list"></i>
        </div>
        <div class="ms-3">
            <h4>后台管理系统</h4>
        </div>
        <div class="ms-auto" id="mobile-user-info">
            <!-- 移动端用户信息 -->
        </div>
    </div>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 p-0 sidebar d-flex flex-column" id="sidebar">
                <!-- 侧边栏顶部标题 -->
                <div class="sidebar-header">
                    <h4>后台管理系统</h4>
                    <div class="toggle-sidebar d-none d-md-block" id="toggle-sidebar">
                        <i class="bi bi-chevron-left"></i>
                    </div>
                </div>
                
                <!-- 侧边栏菜单 -->
                <div class="sidebar-menu">
                    <ul class="nav flex-column" id="sidebar-menu">
                        <!-- 菜单将通过AJAX动态加载 -->
                    </ul>
                </div>
                
                <!-- 侧边栏底部版权信息 -->
                <div class="sidebar-footer">
                    © 2025 管理系统 版权所有
                </div>
            </div>
            
            <!-- 主内容区域 -->
            <div class="col-md-10 p-0 main-content d-flex flex-column" id="main-content">
                <!-- 顶部导航栏 -->
                <div class="top-nav d-none d-md-flex justify-content-between align-items-center px-4">
                    <div>
                        <h4 id="module-title">后台管理系统</h4>
                    </div>
                    <div id="user-info">
                        <!-- 用户信息将通过AJAX动态加载 -->
                    </div>
                </div>
                
                <!-- 标签页导航 -->
                <div id="tabs-container">
                    <!-- 标签页将动态生成 -->
                </div>
                
                <!-- 主要内容 -->
                <div class="flex-grow-1 p-4" id="page-content">
                    <div id="iframe-container">
                        <!-- iframe将在这里动态生成 -->
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        // 认证相关函数
        const Auth = {
            // 获取token
            getToken: function() {
                return localStorage.getItem('token');
            },
            
            // 设置token
            setToken: function(token) {
                localStorage.setItem('token', token);
            },
            
            // 移除token
            removeToken: function() {
                localStorage.removeItem('token');
            },
            
            // 检查是否已登录
            isLoggedIn: function() {
                return !!this.getToken();
            },
            
            // 登出
            logout: function() {
                this.removeToken();
                window.location.href = '/login';
            }
        };

        // 首页URL
        const dashboardUrl = '/admin/dashboard';
        
        // 标签页管理
        const TabManager = {
            tabs: {},
            activeTabId: null,
            
            // 初始化
            init: function() {
                // 添加首页标签
                this.addTab(dashboardUrl, '仪表盘');
               
                
                // 绑定标签切换事件
                $(document).on('click', '.nav-tab', function(e) {
                    if (!$(e.target).hasClass('close-tab')) {
                        const tabId = $(this).data('id');
                        TabManager.activateTab(tabId);
                    }
                });
                
                // 绑定关闭标签事件
                $(document).on('click', '.close-tab', function(e) {
                    e.stopPropagation();
                    const tabId = $(this).parent().data('id');
                    TabManager.closeTab(tabId);
                });
            },
            
            // 添加标签
            addTab: function(id, title) {
                // 如果标签已存在，则激活它
                if (this.tabs[id]) {
                    this.activateTab(id);
                    return;
                }
                
                // 创建iframe
                const iframeId = `iframe-${id.replace(/[^a-zA-Z0-9]/g, '-')}`;
                const $iframe = $(`<iframe id="${iframeId}" src="${id}" class="tab-iframe" style="width:100%; height:100%; border:none; display:none;"></iframe>`);
                $('#iframe-container').append($iframe);
                
                // 创建新标签
                this.tabs[id] = {
                    id: id,
                    title: title,
                    iframeId: iframeId
                };
                
                // 创建标签DOM
                const tabHtml = `<div class="nav-tab" data-id="${id}">
                    <span>${title}</span>
                    ${id !== dashboardUrl ? '<i class="bi bi-x close-tab"></i>' : ''}
                </div>`;
                
                // 如果是首页标签，插入到最前面
                if (id === dashboardUrl) {
                    $('#tabs-container').prepend(tabHtml);
                } else {
                    $('#tabs-container').append(tabHtml);
                }
                
                // 激活新标签
                this.activateTab(id);
            },
            
            // 激活标签
            activateTab: function(id) {
                if (!this.tabs[id]) {
                    // 如果标签不存在，并且也不是首页，则激活首页
                    if (id !== dashboardUrl) {
                        this.activateTab(dashboardUrl);
                    }
                    return;
                }
                
                // 移除其他标签的激活状态
                $('.nav-tab').removeClass('active');
                $('.tab-iframe').hide();
                
                // 设置当前标签为激活状态
                $(`.nav-tab[data-id="${id}"]`).addClass('active');
                
                // 显示对应的iframe
                $(`#${this.tabs[id].iframeId}`).show();
                
                // 更新标题
                $('#module-title').text(this.tabs[id].title);
                
                // 记录当前激活的标签
                this.activeTabId = id;
                
                // 标记对应的菜单为活动状态
                markActiveMenuItem();
            },
            
            // 关闭标签
            closeTab: function(id) {
                if (!this.tabs[id] || id === dashboardUrl) return;
                
                // 移除标签DOM和iframe
                $(`.nav-tab[data-id="${id}"]`).remove();
                $(`#${this.tabs[id].iframeId}`).remove();
                
                // 如果关闭的是当前激活的标签，则激活前一个标签
                if (this.activeTabId === id) {
                    const tabIds = Object.keys(this.tabs);
                    const currentIndex = tabIds.indexOf(id);
                    const newActiveId = currentIndex > 0 ? tabIds[currentIndex - 1] : tabIds[0];
                    
                    // 删除标签对象
                    delete this.tabs[id];
                    
                    // 激活新标签
                    this.activateTab(newActiveId);
                } else {
                    // 删除标签对象
                    delete this.tabs[id];
                }
            },
            
            // 加载新页面到标签
            loadPageToTab: function(url, title) {
                // 加载页面到标签
                this.addTab(url, title);
            }
        };
        
        // AJAX请求设置
        $.ajaxSetup({
            beforeSend: function(xhr) {
                const token = Auth.getToken();
                if (token) {
                    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                }
            },
            error: function(xhr) {
                if (xhr.status === 401) {
                    // 认证失败，重定向到登录页
                    Auth.removeToken();
                    window.location.href = '/login';
                }
            }
        });
        
        // 页面加载时检查登录状态
        $(document).ready(function() {
            // 如果未登录，则重定向到登录页
            if (!Auth.isLoggedIn()) {
                window.location.href = '/login';
                return;
            }
            
            // 加载用户信息和菜单
            loadUserInfo();
            loadMenus1();
            
            // 初始化标签页管理
            TabManager.init();
            
            // 绑定侧边栏折叠按钮事件
            $('#toggle-sidebar').click(function() {
                $('#sidebar').toggleClass('collapsed');
                $('#main-content').toggleClass('expanded');
                
                // 切换折叠图标
                const icon = $(this).find('i');
                if (icon.hasClass('bi-chevron-left')) {
                    icon.removeClass('bi-chevron-left').addClass('bi-chevron-right');
                } else {
                    icon.removeClass('bi-chevron-right').addClass('bi-chevron-left');
                }
            });
            
            // 绑定移动端菜单切换按钮事件
            $('#mobile-menu-toggle').click(function() {
                $('#sidebar').toggleClass('show');
            });
            
            // 点击页面内容区域隐藏移动端菜单
            $('#main-content').click(function() {
                if ($('#sidebar').hasClass('show')) {
                    $('#sidebar').removeClass('show');
                }
            });
            
            // 监听标签切换，更新活动菜单
            // $(document).on('DOMSubtreeModified', '#tabs-container', function() {
            //     setTimeout(markActiveMenuItem, 100);
            // });
        });
        
        // 加载用户信息
        function loadUserInfo() {
            $.ajax({
                url: '/api/user/info',
                type: 'GET',
                success: function(response) {
                    const userInfoHtml = `
                        <span class="me-3">欢迎，${response.name}</span>
                        <button class="btn btn-sm btn-outline-secondary" onclick="Auth.logout()">退出</button>
                    `;
                    $('#user-info').html(userInfoHtml);
                    $('#mobile-user-info').html(`
                        <span>${response.name}</span>
                    `);
                }
            });
        }
        
        // 加载菜单
        function loadMenus1() {
            $.ajax({
                url: '/api/menus/user',
                type: 'GET',
                success: function(response) {
                    const menuTree = response.menu_tree;
                    renderMenus(menuTree);
                },
                error: function(error) {
                    console.error('Failed to load menus', error);
                }
            });
        }
        
        // 渲染菜单
        function renderMenus(menuTree) {
            const $menu = $('#sidebar-menu');
            $menu.empty();

                                   
            // 渲染菜单树
            menuTree.forEach(function(menu) {
                renderMenuItem(menu, $menu);
            });
            
            // 绑定菜单点击事件，使用标签页打开
            $('.menu-link').click(function(e) {
                e.preventDefault();
                const url = $(this).attr('href');
                const title = $(this).data('title') || $(this).text().trim();
                
                // 如果url为#，则不打开
                if (url === "#") {
                    return;
                }

                // 如果url为http://或https://，则在新窗口打开
                if (url.startsWith('http://') || url.startsWith('https://')) {
                    window.open(url, '_blank');
                } else {
                    // 在标签页中打开链接
                    TabManager.loadPageToTab(url, title);
                }

                
                // 在移动端上关闭侧边栏
                if (window.innerWidth < 768) {
                    $('#sidebar').removeClass('show');
                }
            });
        }
        
        // 渲染菜单项
        function renderMenuItem(menu, $parent) {
            // 创建菜单项
            const hasChildren = menu.children && menu.children.length > 0;
            const itemClass = hasChildren ? 'nav-item has-submenu' : 'nav-item';
            
            const $item = $(`
                <li class="${itemClass}">
                    <a class="nav-link menu-link" href="${menu.path}" data-title="${menu.name}">
                        <i class="bi ${menu.icon || 'bi-grid'}"></i><span>${menu.name}</span>
                    </a>
                </li>
            `);
            
            $parent.append($item);
            
            // 如果有子菜单，创建子菜单容器
            if (hasChildren) {
                const $subMenu = $('<ul class="submenu nav flex-column"></ul>');
                $item.append($subMenu);
                
                // 为每个子菜单项调用渲染函数
                menu.children.forEach(function(child) {
                    renderMenuItem(child, $subMenu);
                });
                
                // 绑定点击事件用于展开/折叠子菜单
                $item.children('a').click(function(e) {
                    if ($(window).width() > 768) {
                        // 桌面模式时，如果有子菜单，则展开/折叠
                        if (hasChildren) {
                            e.preventDefault();
                            e.stopPropagation();
                            
                            $(this).parent().toggleClass('open');
                            $(this).siblings('.submenu').toggleClass('show');
                        }
                    } else {
                        // 移动模式，直接允许连接点击
                        if (!hasChildren) {
                            // 无子菜单时，关闭侧边栏
                            $('#sidebar').removeClass('show');
                        }
                    }
                });
            }
        }
        
        // 添加标记当前活动菜单的函数
        function markActiveMenuItem() {
            // 获取当前页面URL路径
            let currentPath = TabManager.activeTabId || window.location.pathname;
            
            // 清除所有活动标记
            $('.nav-link').removeClass('active');
            
            // 查找并标记当前活动的菜单项
            $(`.menu-link[href="${currentPath}"]`).addClass('active');
            
            // 如果是子菜单项，展开其父级菜单
            const $activeSubMenuItem = $(`.submenu .menu-link[href="${currentPath}"]`);
            if ($activeSubMenuItem.length > 0) {
                $activeSubMenuItem.parents('.has-submenu').addClass('open');
                $activeSubMenuItem.parents('.submenu').addClass('show');
            }
        }
    </script>
</body>
</html> 